package tech.eyao.hs60x.user.controller;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.rong.RongCloud;
import io.rong.models.TokenResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import tech.eyao.hs60x.common.CommonConstants;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.exception.Hs60xException;
import tech.eyao.hs60x.model.domain.AccountDO;
import tech.eyao.hs60x.service.AccountService;
import tech.eyao.hs60x.utils.TokenUtils;

@Api("容云获取token")
@RestController
@RequestMapping(value="/rongcloud")
public class RongcloudController {
	
	private static final Logger logger = LoggerFactory.getLogger(RongcloudController.class);
	@Autowired
	private AccountService accountService;
	
	@Value("${head.url}")
    private String ip;

	@PostMapping(value="/getToken.do")
    @ApiOperation(value = "容云获取token")
	public BaseResult getToken() {
		Map<String, String> map = new HashMap<>();
		try {
			RongCloud rongCloud = RongCloud.getInstance(CommonConstants.RONG_KEY, CommonConstants.RONG_APPSECRET);
			if(null == rongCloud) {
				throw new Hs60xException("链接rongcloud失败！");
			}
			AccountDO accountDO = accountService.getAccountById(TokenUtils.getUserId());
			
			TokenResult tokenResult = rongCloud.user.getToken(String.valueOf(accountDO.getId()), accountDO.getNickName(), ip + "/hs60x/images/" + accountDO.getHeadUrl());
			if(null == tokenResult) {
				throw new Hs60xException("rongcloud get token fail!");
			}
			map.put("rongToken", tokenResult.getToken());
		} catch (Exception e) {
			logger.error("RongcloudController getToken error.", e);
		}
		
		return BaseResult.isSuccess(map);
	}
}
